package cn.tq365.type.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import com.baidu.api.sem.sms.v2.ScheduleType;

/**
 * List<String>与以逗号分割的字符串的相互转换处理类
 * 
 * @author lili
 * 
 */
@MappedTypes(value = { List.class })
@MappedJdbcTypes(JdbcType.NVARCHAR)
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			List<String> parameter, JdbcType jdbcType) throws SQLException {
		if (parameter instanceof List) {
			List<String> param = (List<String>) parameter;
			String pstr = "";
			for (String value : param) {
				pstr = pstr + value + ",";
			}
			if (!StringUtils.isBlank(pstr)) {
				ps.setString(i, pstr.substring(0, pstr.length() - 1));
			} else {
				ps.setNull(i, jdbcType.NVARCHAR.TYPE_CODE);
			}
		} else {
			throw new SQLException("参数类型错误，要求的参数类型为：List<String>");
		}
	}

	@Override
	public List<String> getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String rstr = rs.getString(columnName);
		if (StringUtils.isBlank(rstr))
			return null;
		return Arrays.asList(rstr.split(","));
	}

	@Override
	public List<String> getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String rstr = cs.getString(columnIndex);
		if (StringUtils.isBlank(rstr))
			return null;
		return Arrays.asList(rstr.split(","));
	}

	@Override
	public List<String> getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		String rstr = rs.getString(columnIndex);
		if (StringUtils.isBlank(rstr))
			return null;
		return Arrays.asList(rstr.split(","));
	}
}
